<template>
  <div class="register-container">
    <div class="register-box">
      <h2>Sign Up</h2>
      <form @submit.prevent="register">
        <div class="input-group">
          <label for="username">Username</label>
          <input type="text" id="username" v-model="username" placeholder="Enter your username" required />
        </div>
        <div class="input-group">
          <label for="email">Email</label>
          <input type="email" id="email" v-model="email" placeholder="Enter your email" required
            @change="isemail = false" />
        </div>
        <div class="input-group">
          <label for="password">Password</label>
          <input type="password" id="password" v-model="password" placeholder="Enter your password" required />
        </div>
        <div class="input-group">
          <label for="confirmPassword">Confirm Password</label>
          <input type="password" id="confirmPassword" v-model="confirmPassword" placeholder="Confirm your password"
            required />
        </div>
        <button type="submit" class="register-btn">Register</button>
      </form>
      <p class="login-link">Already have an account? <router-link to="/login">Login</router-link></p>
    </div>
  </div>
  <a-modal v-model:open="amodal2" :footer="null" centered :width="600">
    <!-- 倒计时 -->
    <div style="text-align: center; margin-top: 8px;">
      <n-button v-if="countdown <= 0" type="default" @click="sendCode">
        <span style="font-weight: bold;font-size: large;">
          重新发送
        </span>
      </n-button>
      <div v-else style="font-weight: bold;font-size: large;">
        {{ countdown }}秒后重发
      </div>
    </div>
    <div style="height:30px;">
    </div>
    <!-- 验证码输入框 -->
    <div style="display: flex; justify-content: center; gap: 8px; margin-bottom: 16px;">
      <input v-for="i in 6" :key="i" maxlength="1" class="code-input" v-model="codes[i - 1]"
        @input="handleInput(i - 1, $event)" @keydown="handleKeyDown(i - 1, $event)" />
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, nextTick, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/userStore';
import { useServer } from '../components/ts/useServer';
const username = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const userStore = useUserStore();
const router = useRouter();
const { post } = useServer();
const isemail = ref(false)
const mockTestUrl = "https://m1.apifoxmock.com/m1/6951272-6668040-default/api"

const register = () => {
  if (!(username.value && email.value && password.value)) { alert('Please fill in all fields'); return; }
  if (password.value !== confirmPassword.value) {
    alert('Passwords do not match');
    return;
  }
  //停用
  // if (isemail.value === false) {
  //   confirm_email_verify()
  //   return
  // }
  post('register', { username: username.value, user_email: email.value, user_password: password.value }).then(res => {
    //console.log(res)
    if (res.success) {
      message.success('注册成功')
      router.push('/login')
      // userStore.login(res.userID, res.username);
      // router.push('/');
    } else {
      alert('Invalid email or password');
      console.log('注册失败', res)
    }
  });

};
const amodal2 = ref(false);
const codes = ref(Array(6).fill("")); // 存储6位验证码
const countdown = ref(60);
let codetimer: any = null;
const resetcode = () => {
  codes.value = Array(6).fill("");

}
const verifyEmailCode = ref('')

const sendCode = () => {
  countdown.value = 60;
  clearInterval(codetimer);
  post('sendEmailCode', { email: email.value }, mockTestUrl).then(res => {
    if (res.success) {
      verifyEmailCode.value = res.email_code
      console.log('收到验证码:', verifyEmailCode.value)
    } else {
      message.error('发送失败')
    }
  });
  codetimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      resetcode()
      verifyEmailCode.value = ''
      clearInterval(codetimer);
    }
  }, 1000);
};
const confirm_email_verify = () => {
  amodal2.value = true;
  resetcode()
  sendCode()
}
const handleInput = (index: number, event: any) => {
  const value = event.target.value;
  codes.value[index] = value;

  // 判断是否输入完成
  if (index >= 5 && codes.value.join('').length === 6) {
    if(countdown.value<=0){
      message.error('验证码已过期')
      return
    }
    if (codes.value.join('') === verifyEmailCode.value) {
      message.success('验证成功')
      isemail.value = true
      amodal2.value = false;
      resetcode()
    } else {
      message.error('验证失败')
    }
  }

  // 自动跳到下一个输入框
  if (value && index < 5) {
    const nextInput = event.target.nextElementSibling;
    if (nextInput) {
      nextTick(() => {
        nextInput.focus();
      });
    }
  }
};
const handleKeyDown = (index: number, event: any) => {
  // 处理删除操作
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling;
    if (prevInput) {
      nextTick(() => {
        prevInput.focus();
      });
    }
  }
};

onUnmounted(() => {
  clearInterval(codetimer);
});
</script>

<style scoped lang="scss">
/* 基本布局 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  //background-color: #f0f4f8;
    background: url('@/assets/images/loginback.png') no-repeat center center fixed;
  background-size: cover;
}

.register-box {
  background-color: #fff;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  text-align: center;

}

h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

/* 输入框样式 */
.input-group {
  margin-bottom: 20px;
  text-align: left;
}

.input-group label {
  font-size: 14px;
  color: #666;
}

.input-group input {
  width: 100%;
  padding: 10px;
  margin-top: 8px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s ease;
}

.input-group input:focus {
  border-color: #007bff;
}

/* 按钮样式 */
.register-btn {
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.3);
}

.register-btn:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 123, 255, 0.4);
}

.register-btn:active {
  transform: translateY(0);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.3);
}

/* 登录链接 */
.login-link {
  margin-top: 20px;
  font-size: 14px;
}

.login-link a {
  color: #007bff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.code-input {
  width: 80px;
  height: 100px;
  text-align: center;
  font-size: 72px;
  caret-color: transparent; //隐藏光标
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-box {
    padding: 20px;
  }

  h2 {
    font-size: 20px;
  }

  .register-btn {
    font-size: 16px;
  }
}
</style>
